package com.example.entity;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author lbwxxc
 * @date 2025/4/5 18:05
 * @description: 将一个实体类转换成另一个实体类
 */
public interface BaseData {

    default <V> V asViewObject(Class<V> clazz) {
        try {
            Field[] declaredFields = clazz.getDeclaredFields();
            Constructor<V> constructor = clazz.getConstructor();
            V v = constructor.newInstance();
            for (Field field : declaredFields) {
                convert(field, v);
            }
            return v;
        } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    private void convert(Field field, Object vo) {
        try {
            Field source = this.getClass().getField(field.getName());
            field.setAccessible(true);
            field.setAccessible(true);
            field.set(vo, source.get(this));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
